package com.xs.ai.services;

import com.xs.ai.limiter.DynamicRateLimiter;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
public class BusinessService {

    @Autowired
    private DynamicRateLimiter rateLimiter;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final CircuitBreaker circuitBreaker;

    public BusinessService() {
        this.circuitBreaker = CircuitBreaker.ofDefaults("backend");
    }

    public String processRequest() {
        if (!rateLimiter.tryAcquire()) {
            return "Rate limited!";
        }

        if (!circuitBreaker.tryAcquirePermission()) {
            return fallback();
        }

        try {
            Future<String> future = executor.submit(this::remoteCall);
            return future.get(100, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            circuitBreaker.onError(0, TimeUnit.MILLISECONDS, e);
            return fallback();
        }
    }

    private String remoteCall() throws InterruptedException {
        return "Success!";
    }

    @io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker(name = "backend")
    private String fallback() {
        return redisTemplate.opsForValue().get("fallback:response");
    }

    @Scheduled(fixedRate = 60000)
    public void preloadFallback() {
        redisTemplate.opsForValue().set("fallback:response", "Cached fallback");
    }
}
